<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Common;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Curl;
use App\Http\Controllers\ErrorCode;
use App\Http\Controllers\SuccessCode;
use App\Model\AppDownload;
use App\Model\ChairmanPackage;
use App\Model\GameConfig;
use App\Model\GameList;
use Illuminate\Http\Request;
use Ramsey\Uuid\Uuid;
use Storage;

class Package extends Controller
{
    use Common;

    public function index(Request $request)
    {
        $gameId = $request->input('game_id', '');
        $channelId = $request->input('channel_id', '');
        //打包成功通知地址
        $notifyUrl = $request->input('notify_url', '');
        $uid = $request->input('uid', '');

        if (!$gameId) {
            return $this->getView([], ErrorCode::GAMEID_EMPTY);
        }

        $findData = GameList::where('game_id', $gameId)->first();

        if (!$findData){
            return $this->getView([],ErrorCode::GAME_CONFIG_ERROR);
        }

        $filePath = $findData->package_path;


        $filename = Storage::url('app/' . $filePath);

        if (!file_exists(base_path('storage/app/' . $filePath))) {
            return $this->getView([], ErrorCode::FILE_NOT_EXIST);
        }

        $data = [
            'game_id' => $gameId,
            'channel_id' => $channelId,
            'status' => 1,
            'type' => $request->input('type', 'APK'),
            'addTime' => time(),
        ];
        $id = ChairmanPackage::insertGetId($data);
        $findGameConfig = GameConfig::where('game_id', $gameId)->first();

        $taskData = [
            'target_apk' => $filename,
            'dir' => 'unPackage_apk_temp_' . uniqid(),
            'channel' => $channelId,
            'is_public' => true,
            'new_apk_name' => Uuid::uuid1()->getHex() . '.apk',
            'game_id' => $id,
            'notify_url' => $notifyUrl,
            'true_game_id' => $gameId,
            'uid' => $uid,
            'hot_cloud_id' => $findGameConfig ? $findGameConfig->hot_cloud_id : '',
            'download_url' =>  config('web.cdn_url') . 'package/'.$id
        ];

        $redis = new \Redis;
        $redis->connect(config('web.redis.host'), config('web.redis.port'));

        $taskId = $redis->lpush("package", json_encode($taskData));

        if ($id) {
            return $this->getView([], SuccessCode::ADD_SUCCESS);
        } else {
            return $this->getView([], ErrorCode::ADD_ERROR);
        }
    }

    //游戏下载
    public function download($id)
    {
        $collect = ChairmanPackage::find($id);

        $appDownLoad = new AppDownload();
        $appDownLoad->app_id = $collect->game_id;
        $appDownLoad->down_time = time();
        $appDownLoad->source = 2;
        $appDownLoad->save();

        if ($collect &&  file_exists(base_path($collect->file_path))){
            return response()->download(realpath(base_path($collect->file_path)));
        }
        return '游戏不存在';
    }
}
